<?php
namespace app\admin\controller;

use app\admin\exception\AdminException;
use app\common\entity\Orders;
use app\common\entity\User;
use app\common\entity\LegalConfig;
use app\common\entity\LegalReportcentre;
use app\common\entity\LegalReturnlog;
use think\Request;
use think\Db;
use app\common\command\InitMenu;

class Legal extends Admin
{

    /**
     * @power 报单中心|基础设置
     * @method POST
     */
    public function set(Request $request)
    {   	
    	
    		return $this->render('set', [
            'list' => LegalConfig::where('type', 1)->where('status',1)->select()
        ]);
    }

    /**
     * 添加设置
     */
    public function setadd(Request $request)
    {	
    	$config = new LegalConfig();
    	$config->name = $request->post('name');
        $config->key = $request->post('key');
        $config->value = $request->post('value');
    	
        if ($config->save() === false) {
            throw new AdminException('添加失败');
        }
        return ['code' => 0, 'message' => '添加成功'];
    }

    /**
     * 保存设置
     */
    public function setsave(Request $request)
    {
        $key = $request->post('key');
        $value = $request->post('value');
        $config = LegalConfig::where('key', $key)->find();
        if (!$config) {
            throw new AdminException('操作错误');
        }
        $config->value = $value;
        if ($config->save() === false) {
            throw new AdminException('修改失败');
        }
        return ['code' => 0, 'message' => '配置成功'];
    }

    /**
     * @power 报单中心|报单记录
     * @method POST
     */
    public function index(Request $request)
    {       
        $LegalReportcentre = new LegalReportcentre(); 

        $list = $this->search($request);

        foreach ($list as &$value) {

            $value['helpmobile'] = '';

            if($value['help_id'] != 0){
                $help = User::where('id',$value['help_id'])->find();
                $value['helpname'] = $help['nick_name'];
                $value['helpmobile'] = $help['mobile'];
            }
        }

        return $this->render('list', [
            'list' => $list,
        ]);
    }

    /**
     * @power 报单中心|出售订单
     * @method POST
     */
    public function sale(Request $request)
    {     

        $list = $this->dealsearch($request);

        return $this->render('sale', [
            'list' => $list,
        ]);

    }
    

  

     /**
     * @power 报单中心|报单记录@处理报单
     * @method GET
     */
    public function update(Request $request)
    {
        $do = $request->request('do')??'';
        $id = $request->request('id');
        $order = LegalReportcentre::where('id', $id)->find();

        $LegalReportcentre = new LegalReportcentre();

        if (!$order ||$order['status'] !=0 ) {
            throw new AdminException('订单有误');
        }


        //完成
        if($do=='achieve'){
            //查看当前报单会员信息
            $mem = User::where('id',$order['user_id'])->find();

    

            //配置
            $LegalConfig = new LegalConfig();
            //比例
            $exchangeratio = $LegalConfig->getValue('exchangeratio');

            //增加时间
            $returntime = $LegalConfig->getValue('returntime');

            $addcoin = floor($order['money'] / $exchangeratio * 100)/100;

            Db::startTrans();
            try {
                $User = new User();

                //增加币种
                $User->setBonus($order['user_id'],'coin',$addcoin,'报单增加');
                $User->setBonus($order['user_id'],'cointime',$returntime,'报单增加');

                $LegalReportcentre->where('id',$id)->update(['status'=>1,'approvaltime'=>time(),'amoun'=>$addcoin]);

                Db::commit();

            } catch (\Exception $e) {

                Db::rollback();
            }


        }else if($do=='cancel'){
        //取消
            $LegalReportcentre->where('id',$id)->update(['status'=>-1,'approvaltime'=>time()]);
        }

        return json(['code' => 0, 'message' => '处理成功']);
        
    }


    protected function dealsearch($request,$status = '')
    {
        $query = LegalReturnlog::alias('o')->field('o.*,s.nick_name,s.mobile');

        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'mobile':
                    $query->where('s.mobile', $keyword);
                    break;
            }
            $map['type'] = $type;
            $map['keyword'] = $keyword;
        }

        $startTime = $request->get('startTime');
        $endTime = $request->get('endTime');

        if($startTime && $endTime){
            $query->where('createtime', '<', strtotime($endTime))
            ->where('createtime', '>=', strtotime($startTime));
            $map['startTime'] = $startTime;
            $map['endTime'] = $endTime;
        }

        $userTable = (new User())->getTable();
        $list = $query->leftJoin("$userTable s", 's.id = o.user_id')->order('createtime', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        return $list;
    }

    protected function search($request, $type = '')
    {
        $query = LegalReportcentre::alias('o')->field('o.*,u.nick_name,u.mobile');


        $status = $request->get('status');
        if ($status) {
            $statuss = $status-2;
            $query->where('o.status', $statuss);
            $map['status'] = $status;
        }
        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'mobile':
                    $query->where('u.mobile','like', $keyword);
                    break;
                case 'tid':
                    $query->where('o.tid','like',$keyword);
                    break;
            }
            $map['type'] = $type;
            $map['keyword'] = $keyword;
        }
        $startTime = $request->get('startTime');
        $endTime = $request->get('endTime');
        if($startTime && $endTime){
            $query->where('finishtime', '<', strtotime($endTime))
            ->where('finishtime', '>=', strtotime($startTime));
            $map['startTime'] = $startTime;
            $map['endTime'] = $endTime;
        }

        $userTable = (new User())->getTable();
        $list = $query->leftJoin("$userTable u", 'u.id = o.user_id')
            ->order('createtime', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        return $list;
    }


}
